import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';
import { NzNotificationService } from 'ng-zorro-antd';
import { Router } from '@angular/router';
import { NzModalService, NzModalSubject } from 'ng-zorro-antd';
import {ElevatorInfoBean} from "../../../elevator/elevator-info/bean/elevatorInfo.bean";
import {ContractBean} from "../../bean/contract.bean";
import {ContractProjectBean} from "../../bean/contract-project.bean";
import {Config} from "../../../../service/config";
import {HttpServcie} from "../../../../service/http.service";
import {elevatorTypes} from "../../../../service/constant/elevatorTypeConstant";
import * as moment from "moment";

@Component({
  selector: 'contract-project-add-page',
  templateUrl: 'contract-project-add.html',
  styleUrls: ['contract-project-add.scss']
})
export class ContractProjectAddPage implements OnInit {
  validateForm: FormGroup;
  contractBean = new ContractBean();
  contractProjectBean = new ContractProjectBean();
  elevatorInfo :　ElevatorInfoBean = new ElevatorInfoBean();

  elevatorTypes = elevatorTypes;
  config=Config;
  //获取电梯参数
  list : any = [];
  listSelect : any = [];
  total: string;
  elevatorIds  = [];
  elevatorList = [];
  //地址
  addresOptions: any;
  //省市区
  options: any = [];
  @Input() inValue: any = [];
  @Output("outPut") outPut = new EventEmitter();
  //多选框
  allChecked: any = false;
  indeterminate: any = false;

  // 查询面板
  panels = {
    active: true,
    name: '查询',
    disabled: false,
    childPanel: [
      {
        active: false,
        name: '查询'
      }
    ]
  };

  currentModal: NzModalSubject;
  isConfirmLoading = false;
  modelTitle = "新增";
  updateData: any={}
  modal: any=0;
  totalList: any=[];
  partyType:any;
  partyId:any;
  constructor(
    private fb: FormBuilder,
    private httpServcie: HttpServcie,
    private router: Router,
    private _notification: NzNotificationService,
    private nsub: NzModalSubject,
    private modalService: NzModalService
  ) {
      this.partyType = JSON.parse(window.localStorage['user']).partyType;
      this.partyId = JSON.parse(window.localStorage['user']).partyId;
  }

  ngOnInit() {
    this.validateForm = this.fb.group({
      projectName: [null, [Validators.required]],
      projectAddress: [null, [Validators.required]],
      onePrice: [null, [Validators.required]],
      starTime: [null, [Validators.required]],
      endTime: [null, [Validators.required]],
      addresOptions: [null, [Validators.required]], //项目地址
      elevatorIds : [null, []],
    });
    if (this.inValue) {
      this.contractProjectBean.contractId = this.inValue;
    }
  }

  /**
   * 提交合同新增项目
   */
  submitForm() {
    //校验是否能提交
    //没有填的标红
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
    }
    //处理是否提交
    for (const i in this.validateForm.controls) {
      if (!this.validateForm.controls[i].valid) {
        return;
      }
    }
    if (this.addresOptions) {
      //省
      this.contractProjectBean.projectProvince = this.addresOptions[0];
      //市
      this.contractProjectBean.projectCity = this.addresOptions[1];
      //区
      this.contractProjectBean.projectArea = this.addresOptions[2];
    }
    if (this.contractProjectBean.starTime) {
      this.contractProjectBean.starTime = moment(this.contractProjectBean.starTime).format(
        "YYYYMMDD"
      );
    }
    if (this.contractProjectBean.endTime) {
      this.contractProjectBean.endTime = moment(this.contractProjectBean.endTime).format(
        "YYYYMMDD"
      );
    }
    this.contractProjectBean.elevatorCount = this.elevatorIds.length;
    this.httpServcie.addContractProject(this.contractProjectBean).subscribe(
      data => {
        if (data.status == 200) {
          this._notification.create("success", "成功提示", "新增成功");
          this.outPut.emit(data);
        } else {
          this._notification.create("error", "错误提示", data.message);
        }
      },
      error => {
        console.log("fail");
      }
    );
  }

  addElevator(title, content, footer){
    if (this.partyType != '1') {
      this._notification.create("error", "错误提示", "您无权限");
      return;
    }
    this.elevatorInfo.pageSize = 10;
    this.elevatorInfo.currentPage = 1;
    this.modelTitle = "添加电梯";
    this.modal = 0;
    this.query();
    this.currentModal = this.modalService.open({
      title: title,
      content: content,
      footer: footer,
      maskClosable: false,
      width: 1200,
      zIndex: 2000,
      style: {
        top: "20px"
      },
      onOk() {
        console.log("Click ok");
      }
    });
  }

  /**
   * 获取电梯
   */
  query(){
    this.elevatorInfo.maintenancePartyId = this.partyId;
    this.httpServcie.demandMaintGetElevators(this.elevatorInfo).subscribe(
      data => {
        if (data.status == 200) {
          this.list = data.data.list;
          this.listSelect = data.data.listSelect;
          this.total = data.data.total;
          //再次点击，回显已选择
          this.list.forEach(element1 => {
            this.elevatorIds.forEach(element2 => {
              if (element1.id == element2) {
                element1.checked = true;
              }
            });
          });
        } else if (data.status === 401) {
          this.router.navigateByUrl("/login");
          return;
        } else {
          // 异常
          this._notification.create("error", "错误提示", data.message);
        }
      },
      error => {
        console.log(JSON.stringify(error));
      }
    );
  }

  /**
   * 保存勾选的电梯
   */
  saveElevators(){
    //再次点击时重新给值
    const tempList: any = [];
    this.list.forEach(element => {
      let isNotExist = true;
      if (element.checked) {
        tempList.push(element);
        this.elevatorIds.forEach(element1 =>{
          if(element.id == element1){
            isNotExist = false;
          }
        });
        if(isNotExist){
          this.elevatorIds.push(element.id + "");
          this.elevatorList.push(element.elevatorNum + "");
        }
      }
    });
    this.contractProjectBean.elevatorIds = this.elevatorIds.join(",");
    this.contractProjectBean.elevatorList = this.elevatorList.join(",");
    if (tempList.length == 0) {
      // 异常
      this._notification.create("error", "错误提示", "至少选中一条数据！");
      return;
    }
    this.currentModal.destroy();
  }

  clear(){
    this.contractProjectBean.elevatorIds = "";
    this.elevatorIds.splice(0,this.elevatorIds.length);

    this.contractProjectBean.elevatorList = "";
    this.elevatorList.splice(0,this.elevatorList.length);
  }

  loadData(e: {
    option: any;
    index: number;
    resolve: Function;
    reject: Function;
  }): void {
    if (e.index === -1) {
      e.resolve(this.httpServcie.getProvince());
      return;
    }
    const option = e.option;
    option.loading = true;
    if (e.index === 0) {
      let values: any = option["value"];
      let valueList = this.httpServcie.getCity(e.option);
      let cities: any = {};
      cities[values] = valueList;

      setTimeout(() => {
        option.loading = false;
        e.resolve(cities[option.value]);
      }, 1);
    }
    if (e.index === 1) {
      let value = option["value"];
      let valueList = this.httpServcie.getRelation(e.option);
      let scenicspots: any = {};
      scenicspots[value] = valueList;
      setTimeout(
        () => {
          option.loading = false;
          e.resolve(scenicspots[option.value]);
        },
        1,
        scenicspots,
        option
      );
    }
  }

//全选
  checkAll(value) {
    if (value) {
      this.list.forEach(data => {
        if (!data.disabled) {
          data.checked = true;
        }
      });
    } else {
      this.list.forEach(data => data.checked = false);
    }
  };

  //table加载数据时
  displayDataChange($event) {
    this.list = $event;
    this.refreshStatus();
  }

  //重置选择框
  refreshStatus() {
    const allChecked = this.list.every(value => value.disabled || value.checked);
    const allUnChecked = this.list.every(value => value.disabled || !value.checked);
    this.allChecked = allChecked;
    this.indeterminate = (!allChecked) && (!allUnChecked);
  }

  //添加添加页面的数据
  handleOk(e){
    this.isConfirmLoading = true;
    setTimeout(() => {
      /* destroy方法可以传入onOk或者onCancel。默认是onCancel */
      this.currentModal.destroy();
      this.isConfirmLoading = false;
      this.currentModal = null;
    }, 500);
  }

  //添加后返回的结果
  addOutPut(event) {
    this.isConfirmLoading = true;
    setTimeout(() => {
      /* destroy方法可以传入onOk或者onCancel。默认是onCancel */
      this.currentModal.destroy();
      this.isConfirmLoading = false;
      this.currentModal = null;
    }, 500);
    this.query();
  }


  //分页
  nzPageSizeChange(event) {
    this.elevatorInfo.pageSize = event;
    this.elevatorInfo.currentPage = 1;
    this.query();

  }

  //输入框的方法
  nzPageIndexChange(event) {
    this.elevatorInfo.currentPage = event;
    this.query();
  }

  //当前页
  nzPageIndexClickChange(event) {
    this.elevatorInfo.currentPage = event;
    this.query();
  }

  //交验
  getFormControl(name) {
    return this.validateForm.controls[name];
  }
}
